package com.ruoyi.qywx.getway.api;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.qywx.enums.QywxMediaEm;
import com.ruoyi.qywx.getway.keys.QywxKey;

import java.util.concurrent.TimeUnit;

/**
 * @author : hcl
 * @Date : 2023/8/22 09:41
 * 获取企业微信临时素材mediaId
 */
public class QyMediaUtil {
    private static final RedisCache redis;

    static {
        redis = SpringUtils.getBean(RedisCache.class);
    }

    public static String getImageMediaId(Meta meta, String url) {
        return getMediaId(meta, QywxMediaEm.IMAGE, null, url);
    }

    public static String getFileMediaId(Meta meta, String name, String url) {
        return getMediaId(meta, QywxMediaEm.IMAGE, name, url);
    }

    public static String getMediaId(Meta meta, QywxMediaEm media, String name, String url) {
        if (StrUtils.isEmpty(url)) {
            return StrUtil.EMPTY;
        }
        String key = QywxKey.RedisKey.temporaryMediaKey(url);
        String mediaId = redis.getCacheObject(key);
        if (StrUtils.isNotEmpty(mediaId)) {
            return mediaId;
        }
        mediaId = QyMediaApi.mediaUpload(meta, media, name,url);
        if (StrUtils.isNotEmpty(mediaId)) {
            redis.setCacheObject(key, mediaId, 71, TimeUnit.HOURS);
            return mediaId;
        }
        return StrUtils.EMPTY;
    }
}
